﻿using Admin.Core.Common.Attributes;
using Admin.Core.Common.Auth;
using Admin.Core.Common.Configs;
using Admin.Core.Common.Extensions;
using Admin.Core.Common.Helpers;
using Admin.Core.Common.Output;
using Admin.Core.Model.Quality;
using Admin.Core.Repository.Admin;
using Admin.Core.Repository.Quality;
using Admin.Core.Service.TimingTask.Output;
using AutoMapper;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.TimingTask
{
    public class TimingTaskService: ITimingTaskService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly AppConfig _appConfig;
        private readonly IMachineCheckRepository _machineCheckRepository;
        private readonly EmailHelper _emailHelper;
     
        public TimingTaskService(IUser user, IMapper mapper
            ,IOptionsMonitor<AppConfig> appConfig
            ,EmailHelper emailHelper
            ,IMachineCheckRepository machineCheckRepository)
        {
            _user = user;
            _mapper = mapper;
            _emailHelper = emailHelper;
            _appConfig = appConfig.CurrentValue;
            _machineCheckRepository = machineCheckRepository;
        }
        private  string SendMsg(List<OwnerCheckListOutput> list)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("计量编号");
            dt.Columns.Add("校准类型");
            dt.Columns.Add("设备名称");
            dt.Columns.Add("型号");
            dt.Columns.Add("序列号");
            dt.Columns.Add("设备号");
            dt.Columns.Add("责任人");
            dt.Columns.Add("计划校准日期");

            for (int i = 0; i < list.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["计量编号"] = list[i].ControlNo;
                dr["校准类型"] = list[i].CalType==0?"内部校准":"外部校准";
                dr["设备名称"] = list[i].EquipmentName;
                dr["型号"] = list[i].Model;
                dr["序列号"] = list[i].SerialNo;
                dr["设备号"] = list[i].EquipmentNo;
                dr["责任人"] = list[i].OwnerName;
                dr["计划校准日期"] = list[i].PlanCalTime;
                dt.Rows.Add(dr);

            }

            string MailBody = "<p style=\"font-size: 10pt\">以下内容为系统自动发送，请勿直接回复，谢谢。</p><table cellspacing=\"1\" cellpadding=\"3\" border=\"1\" bgcolor=\"000000\" style=\"font-size: 10pt;line-height: 15px;\">";
            MailBody += "<div align=\"center\">";
            MailBody += "<tr>";
            for (int hcol = 0; hcol < dt.Columns.Count; hcol++)
            {
                MailBody += "<td bgcolor=\"999999\">&nbsp;&nbsp;&nbsp;";
                MailBody += dt.Columns[hcol].ColumnName;
                MailBody += "&nbsp;&nbsp;&nbsp;</td>";
            }
            MailBody += "</tr>";

            for (int row = 0; row < dt.Rows.Count; row++)
            {
                MailBody += "<tr>";
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    MailBody += "<td bgcolor=\"dddddd\">&nbsp;&nbsp;&nbsp;";
                    MailBody += dt.Rows[row][col].ToString();
                    MailBody += "&nbsp;&nbsp;&nbsp;</td>";
                }
                MailBody += "</tr>";
            }
            MailBody += "</table>";
            MailBody += "</div>";
            return MailBody;
        }

        [Transaction]
        public async Task<IResponseOutput> CalSendAsync(int tenant)
        {
            var smtpConfig = _appConfig.Smtp;
            var list = await _machineCheckRepository.Orm.GetGuidRepository<MachineCheckEntity>(t => t.TenantId == tenant && t.IsDeleted == false)
                .Select.Where(x => x.Enabled == true && x.Status != 1 && x.Status != 2).ToListAsync(a=>new OwnerCheckListOutput {  Email =a.Owner.Email, OwnerName =a.Owner.NickName });
            var bgs = list.Select(x => x.OwnerId).Distinct();
            var mailList = new List<string>();
            List<OwnerCheckListOutput> rsList = new List<OwnerCheckListOutput>();
            foreach (var id in bgs)
            {
                List<OwnerCheckListOutput> rs = new List<OwnerCheckListOutput>();
                var ls = list.Where(x => x.OwnerId == id);
                List<long> ll = new List<long>();
                foreach (var check in ls)
                {
                    if (check.CalType == 0)
                    {
                        TimeSpan sp = check.PlanCalTime.Subtract(DateTime.Now);
                        if (sp.Days <= 3)
                        {
                            //check.Status = 0;
                            rs.Add(check);
                            ll.Add(check.Id);
                        }
                    }
                    else if(check.CalType == 1)
                    {
                        TimeSpan sp = check.PlanCalTime.Subtract(DateTime.Now);
                        if (sp.Days <= 15)
                        {
                            //check.Status = 0;
                            rs.Add(check);
                            ll.Add(check.Id);
                        }
                    }
                }

                foreach (var i in ll)
                {
                    var sl = await _machineCheckRepository.Orm.GetGuidRepository<MachineCheckEntity>(t => t.TenantId == tenant && t.IsDeleted == false)
                       .Select.Where(x => x.Id==i).ToOneAsync();
                    sl.Status = 0;
                    var mid = await _machineCheckRepository.UpdateAsync(sl);
                }
                if (rs.Count() > 0)
                {
                    //foreach (var entity in sl)
                    //{
                    //    entity.Status = 0;
                    //}
                    if (!string.IsNullOrEmpty(rs[0].Email))
                    { 
                         mailList.Add(rs[0].Email);
                    }
                    rsList.AddRange(rs);
                }
            }
            await _emailHelper.SendEmailAsync(smtpConfig.Server, smtpConfig.Port, smtpConfig.FromAddress, mailList, "设备校准通知", SendMsg(rsList), smtpConfig.CcAddress);
            return ResponseOutput.Result(true);
        }
        

    }
}
